﻿namespace EasyToolkit.BindingTemplates.SortAndFilter
{
    using System;
    using System.Reflection;
    using EasyToolkit.BindingTemplates.Definitions;
    using EasyToolkit.BindingTemplates.Definitions.Binding;

    public static class SortElementFactory
    {
        static public ISortElement CreateInstance(ITemplateDefinition templateDefinition, IBindingDefinition bindingDefinition, bool descending, bool caseSensitive)
        {
            if (templateDefinition == null || bindingDefinition == null)
                return null;

            MethodInfo createLambdaExpression = typeof(SortElementFactory).GetMethod("CreateInstance", BindingFlags.NonPublic | BindingFlags.Static).MakeGenericMethod(templateDefinition.BindingType.BindType, bindingDefinition.BindingType);
            return createLambdaExpression.Invoke(null, new object[] { bindingDefinition, descending, caseSensitive }) as ISortElement;
        }

        static private ISortElement CreateInstance<T, TT>(IBindingDefinition bindingDefinition, bool descending, bool caseSensitive)
        {
            Type type = typeof(SortElement<,>).MakeGenericType(new System.Type[] { typeof(T), typeof(TT) });
            return Activator.CreateInstance(type, new object[] { bindingDefinition, descending, caseSensitive }) as ISortElement;
        }
    }
}
